<script setup lang="ts">
import { ref, onMounted, provide } from "vue"; //引入 vue 相关函数
import GoodsPanel from "../../../components/GoodsPanel.vue"; //引入公用自定义组件
import GoodsDetails from "../../../components/GoodsDetails.vue"; //引入公用自定义组件
import { getGoodsList } from "../../../api"; //引入 axios 接口
import type { Goods } from "../../../model"; //引入自定义数据类型
//模拟商品数据
const goodsList = ref<Goods[]>([
  {
    name: "减压弹力球",
    picture: "src/assets/images/ball.png",
    description: "释放压力，放松身心",
    price: 199,
  },
]);
//是否显示商品详情
const isShowDetails = ref(false);
//定义商品详情数据对象
const goodsDetails = ref();
//通过 provide 实现跨组件通信
provide("isShowDetails", isShowDetails); //商品详情组件是否显示
//显示商品详情
function showGoodsDetails(goods: Goods) {
  goods.discount = 0.8; //设置商品折扣
  goods.num = 1; //设置商品数量
  goodsDetails.value = goods; //传递商品详情信息
  isShowDetails.value = true; //显示商品详情组件
}
//获得所有商品列表
async function getGoods() {
  const res = await getGoodsList();
  goodsList.value = res.data.data
    .filter((value: Goods) => value.category_id != 38)
    .slice(-4);
}
//页面组件加载完成
onMounted(() => {
  getGoods();
});
</script>
<template>
  <!--引入子组件-->
  <GoodsPanel title="新鲜好物" sub-title="新鲜出炉 品质靠谱">
    <div
      class="goodsItem"
      v-for="item in goodsList"
      @click="showGoodsDetails(item)"
    >
      <div>
        <img :src="item.picture" />
        <div class="discount">8 折</div>
      </div>
      <div>{{ item.name }}</div>
      <div>{{ item.description.replace(/<\/?[^>]+(>|$)/g, "") }}</div>
      <div>
        ￥{{ (item.price * 0.8).toFixed(2)
        }}<span>￥{{ item.price.toFixed(2) }}</span>
      </div>
    </div>
  </GoodsPanel>
  <!--引入商品详情组件-->
  <GoodsDetails :item="goodsDetails"></GoodsDetails>
</template>
<style scoped>
.goodsItem {
  border-radius: 5px;
  width: 270px;
  margin-right: 20px;
  transition: all 0.3s ease;
}
.goodsItem:nth-child(1) {
  margin-left: 15px;
}
.goodsItem:hover {
  box-shadow: 0px 3px 5px 5px lightgray;
  transform: translateY(-5px);
}
.goodsItem > div {
  margin: 10px auto;
  width: 250px;
  position: relative;
}
.goodsItem > div:nth-child(1) {
  text-align: center;
}
.goodsItem > div:nth-child(2) {
  font-size: 20px;
}
.goodsItem > div:nth-child(3) {
  font-size: 14px;
  color: #999999;
}
.goodsItem > div:nth-child(4) {
  font-size: 20px;
  color: #cf4444;
  font-weight: bold;
}
.goodsItem > div:nth-child(4) > span {
  font-size: 14px;
  color: #999999;
  text-decoration: line-through;
  font-weight: normal;
  margin-left: 10px;
}
.goodsItem img {
  width: 250px;
  height: 250px;
  border-radius: 5px;
}
.goodsItem .discount {
  background-color: #cf4444;
  position: absolute;
  top: 0px;
  right: 0px;
  border-radius: 5px;
  color: #ffffff;
  width: 40px;
  height: 25px;
  line-height: 25px;
}
</style>
